<?php
/*
 *
 *      setup-save.php - v1.0.0 @07.07.2009 22:29:40 CEST
 *
 *      StudioGallery Copyright (C) 2009 Rafal Kusior (spuavick) <spuavick@interia.pl>
 *
 *      This program is free software: you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation, either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *      -----------------------------------------------------------------------------
 *
 *      Niniejszy program jest wolnym oprogramowaniem - możesz go rozpowszechniać
 *      dalej i/lub modyfikować na warunkach Powszechnej Licencji Publicznej GNU
 *      wydanej przez Fundację Wolnego Oprogramowania, według wersji 2 tej Licencji
 *      lub dowolnej z późniejszych wersji.
 *
 *      Niniejszy program rozpowszechniany jest z nadzieją, iż będzie on użyteczny -
 *      jednak BEZ ŻADNEJ GWARANCJI, nawet domyślnej gwarancji PRZYDATNOŚCI HANDLOWEJ
 *      albo PRZYDATNOŚCI DO OKREŚLONYCH ZASTOSOWAŃ. Bliższe informacje na ten temat
 *      można uzyskać z Powszechnej Licencji Publicznej GNU.
 *
 *      Kopia Powszechnej Licencji Publicznej GNU powinna zostać ci dostarczona
 *      razem z tym programem. Jeżeli nie została dostarczona, odwiedź
 *      <http://www.gnu.org/licenses/>
 */

$preU = "../";

require_once($preU.'sg_settings.php');

// if ($_SESSION['admin']) { header("Location: ../index.php"); }

if (preg_match("#".$conf['conf_url']."#",$_SERVER['HTTP_REFERER']) && $_SESSION['key'] && $_SESSION['key'] == $_REQUEST['key']) {

	if ($_GET['set'] == 'page') {

		$data = mysql_real_escape_array($_POST);

		$title 		= strip_tags(trim($data['title']));
		$url 		= strip_tags(trim($data['url']));
  		$desc 		= strip_tags(trim($data['desc']));
		$keywords	= strip_tags(trim($data['keywords']));
		$theme		= trim($data['theme']);
		$startpage	= (int)$data['startpage'];
		$page		= (int)$data['page'];
		$blog_page 	= (int)$data['blog_page'];
		$blog_title	= strip_tags(trim($data['blog_title']));
		$page_title = strip_tags(trim($data['page_title']));
		$comments	= (int)$data['comments'];
		$news_item	= (int)$data['blog_item'];
		$email		= strip_tags(trim($data['e-mail']));
		$smtp_pass	= trim($data['smtp_pass']);
		$smtp_host	= strip_tags(trim($data['smtp']));
		$mail		= (int)$data['mail'];
		$error 		= array();
		if ($title == '')
			$error[] = _("Tytuł strony");
		if ($desc == '')
			$error[] = _("Opis strony");
		if ($keywords == '')
			$error[] = _("Słowa kluczowe");
		if (($blog_page == 1 || $startpage == 0) && $blog_title == '')
			$error[] = _("Nazwa blogu/wiadomości");

			// commented - in the future the page.php'll be multipage
// 		if (($page == 1 || $startpage == 1) && $page_title == '')
// 			$error[] = _("Nazwa dodatkowej strony");
		if ($news_item < 1)
			$error[] = _("Ilość wiadomości na stronie");
		$array_keywords = explode(",",$keywords);
		$ile_keywords = count($array_keywords);
		if ($ile_keywords > 25)
			$error[] = _("Maksymalnie 25 słów kluczowych");

		if (count($error) > 0) {

			$i=0;
			echo "<div class=\"error\">";
			echo _("Błędy w formularzu");
			echo ":";

			while($i<count($error)) {

				echo $error[$i];

				if ($i+1 < count($error))
					echo "<br/>";

				$i++;

			}

			echo "</div>";

		} else {

  		$q = $db->select("SELECT conf_id FROM "._pre_."configuration;");
  		$r = $db->get_row($q,'MYSQL_ASSOC');
  		$dane = array(
    					'conf_title'		=> $title,
    					'conf_url'			=> $url,
    					'conf_desc'			=> $desc,
    					'conf_keywords'		=> $keywords,
    					'conf_theme'		=> $theme,
    					'conf_start_page'	=> $startpage,
    					'conf_page'			=> $page,
						'conf_blog'			=> $blog_page,
    					'conf_blog_title'	=> $blog_title,
    					//'conf_page_title'	=> $page_title,
    					'conf_comments'		=> $comments,
    					'conf_news_item'	=> $news_item,
						'conf_email'		=> $email,
						'conf_smtp_host'	=> $smtp_host,
						'conf_smtp_pass'	=> $smtp_pass,
						'conf_mail'			=> $mail
    				);
    	$page = $db->update_array(_pre_."configuration", $dane, "conf_id=".$r['conf_id']);
	if ( $r['conf_theme'] != $theme ) {
		clear_theme_cache();
	}
	if ($sghook->hooks_exist('setup_1_save')) {
	    $sghook->execute_hooks('setup_1_save',$data);
	}
		echo "<div class=\"ok\">";
		echo _("Dane zaktualizowano");
		echo "</div>";
		exit;

		}
	}

	if ($_GET['set'] == 'admin' ) {

		if ($_POST['pass'] && $_POST['admin']) {

    		if ($_POST['pass'] <> $_POST['rpass'])
				header("Location: setup.php?error=".urlencode("podano+różne+hasła"));
			else
				$pass = strip_tags($_POST['pass']);
				$dane = array(
								'conf_admin' => strip_tags($_POST['admin']),
								'conf_pass' => md5($pass)
							);
		} else if($_POST['admin']) {
			$dane = array(
							'conf_admin' => strip_tags($_POST['admin'])
						);
		} else {
			echo _("BŁĄD!");
			exit;
		}

      	$q = $db->select("SELECT conf_id FROM "._pre_."configuration;");
      	$r = $db->get_row($q,'MYSQL_ASSOC');
      	$db->update_array(_pre_."configuration", $dane, "conf_id=".$r['conf_id']);
if ($sghook->hooks_exist('setup_3_save')) {
	    $sghook->execute_hooks('setup_3_save',$_POST);
	}
		echo "<div class=\"ok\">";
		echo _("Dane zaktualizowano");
		echo "</div>";
		exit;

	}

	if ($_GET['set'] == 'photo' ) {

		$data = mysql_real_escape_array($_POST);

		if ($_POST['photo_small'])
			$photo_small = (int)$_POST['photo_small'];
			if ($photo_small < 50)
				$photo_small = 50;
		else
			$photo_small = 50;

		if ($_POST['photo_min'])
			$photo_min = (int)$_POST['photo_min'];
			if ($photo_min < $photo_small)
				$photo_min = 150;
		else
			$photo_min = 150;

		if ($_POST['photo_big'])
			$photo_big = (int)$_POST['photo_big'] > 1024 ? 1024 : (int)$_POST['photo_big'];
		else
			$photo_big = 1024;

		if($_POST['sign_watermark'])
			$sign_watermark = strip_tags($_POST['sign_watermark']);
		else
			if ($_POST['watermark'] == 1)
				$sign_watermark = $conf['conf_title'];
			else
				$sign_watermark = '';

		$dane = array(
						'conf_photo_small' => $photo_small,
						'conf_photo_min' => $photo_min,
						'conf_photo_big' => $photo_big,
						'conf_exif' => (int)$data['exif'],
						'conf_watermark' => (int)$data['watermark'],
						'conf_jquery_lightbox' => (int)$data['jquery_lightbox'],
						'conf_sign_watermark' => $sign_watermark,
						'conf_votes' => $data['votes']
					);

		$q = $db->select("SELECT conf_id FROM "._pre_."configuration;");
		$r = $db->get_row($q,'MYSQL_ASSOC');
		$db->update_array(_pre_."configuration",$dane, "conf_id=".$r['conf_id']);
if ($sghook->hooks_exist('setup_2_save')) {
	    $sghook->execute_hooks('setup_2_save',$data);
	}
		echo "<div class=\"ok\">";
		echo _("Dane zaktualizowano");
		echo "</div>";
		exit;

	}

	if ($_GET['set'] == 'addcategories') {

		$dane = array(
						'cat_name' => strip_tags($_POST['category']),
						'cat_sub_id' => $_POST['subcategory']
					);

		if ($_POST['cat_id'] != 'undefined') {

  			$db->update_array(_pre_."category", $dane, "cat_id=".$_POST['cat_id']);

  		} else {

			$db->insert_array(_pre_."category",$dane);
		}
	}

	if ($_GET['set'] == 'delcat') {

		if ((int)$_POST)
  			$db->select("DELETE FROM "._pre_."category WHERE cat_id=".$_POST['cat']);

	}

	if ( $_GET['set']== 'photos') {

		$font = "../libs/fonts/fonts.otf";
		$katalog = "../photos/";
		$ile = count($_FILES['photo']['name']);
		$i=0;

		$r = $db->select("SELECT conf_photo_small, conf_photo_min, conf_photo_big, conf_watermark, conf_sign_watermark FROM "._pre_."configuration");
		$wym = $db->get_row($r,'MYSQL_ASSOC');

		$small = $wym['conf_photo_small'];
		$min = $wym['conf_photo_min'];
		$big = $wym['conf_photo_big'];
		$text = $wym['conf_sign_watermark'];

		while($i<$ile) {

			if (file_exists($_FILES['photo']['tmp_name'][$i])) {
				 if ( !preg_match("#jp(e)?g#",$_FILES["photo"]['type'][$i]) ) {
					 echo "false"; exit;
				 }

				$name[$i] = strtolower(passGen(32));
				$file = $katalog.$name[$i].".jpg";
				$file_m = $katalog.$name[$i]."_m.jpg";
				$file_h = $katalog.$name[$i]."_h.jpg";
				$file_s = $katalog.$name[$i]."_s.jpg";
				$file_p = $katalog.$name[$i]."_p.jpg";
				$exif[$i] = readExif($_FILES['photo']['tmp_name'][$i]);

				move_uploaded_file($_FILES['photo']['tmp_name'][$i],$file);
				list($poz,$pion) = getimagesize($file);

/**
*		tworzymy dwie miniaturki o rozmiarach podanych w ustawieniach, jeśli zdjęcie nie ma identycznej wysokości z szerokością, stworzymy crop'a
*/
				imageResize($file, $file_s, $small, $small);
				imageResize($file, $file_m, $min, $min);

/**
*		tworzymy zdjęcie na potrzeby specjalnej strony (tuż przed podglądem), jeśli zdjęcie jest szersze niż oryginalny plik, wtedy je zmniejszamy do szerokości 500px; w przeciwnym wypadku jest kopiowane z oryginału i dodawajemy odpowiednią końcówkę _p
*/
				if ($poz > 500 ) {

					$nh = ( 500 * $pion ) / $poz;
					imageResize($file, $file_p, 500, $nh);

				} else {

					$thumb = ImageCreateTrueColor($poz,$pion);
					$source = imagecreatefromjpeg($file);
					imagecopyresampled($thumb,$source, 0, 0, 0, 0, $poz, $pion, $poz, $pion);
					imagedestroy($source);
					imagejpeg($thumb,$file_p,91);
					chmod($file_p,0777);
					imagedestroy($thumb);
				}

/**
*		jeśli zdjęcie jest szersze od wymiarów podanych przez Użytkownika dla maksymalnego rozmiaru, wtedy je pomniejszamy i zapisujemy
*/
				if ($poz > $big ) {

					$thumbsize=$big;
					$imgratio=$poz/$pion;
					$newwidth = $thumbsize;
					$newheight = $thumbsize/$imgratio;
					$thumb = ImageCreateTrueColor($newwidth,$newheight); 	// 500, 253.8
					$source = imagecreatefromjpeg($file);
					imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $poz, $pion);

/**
*		w przypadku ustawienia podpisu w zdjęciu nakładamy go na nie
*/
					if ($conf['conf_watermark'] > 0 && $conf['conf_sign_watermark']) {

						$trans = imagecolorallocatealpha($thumb, 0, 0, 0, 25);
						imagefilledrectangle($thumb, 0, $newheight-40, $newwidth, $newheight, $trans);
						imagealphablending($thumb, true);
						$color = imagecolorallocate($thumb, 255, 255, 255);
						imagettftext($thumb, 16, 0, 20, $newheight-12, $color, $font, $text);

					}

					imagedestroy($source);
					imagejpeg($thumb,$file,91);
					chmod($file,0777);

				} else {

/**
*		jeżeli zdjęcie nie przekracza maksymalnego rozmiaru zdefiniowanego przez Użytkownika, wtedy je zapisujemy bez żadnych modyfikacji
*/
					$newwidth = $poz;
					$newheight = $pion;
					$thumb = ImageCreateTrueColor($newwidth,$newheight); 	// 500, 253.8
					$source = imagecreatefromjpeg($file);
					imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $poz, $pion);

					if ($conf['conf_watermark'] > 0 && $conf['conf_sign_watermark']) {

						$trans = imagecolorallocatealpha($thumb, 0, 0, 0, 25);
						imagefilledrectangle($thumb, 0, $newheight-40, $newwidth, $newheight, $trans);
						imagealphablending($thumb, true);
						$color = imagecolorallocate($thumb, 255, 255, 255);
						imagettftext($thumb, 16, 0, 20, $newheight-12, $color, $font, $text);

					}

					imagedestroy($source);
					imagejpeg($thumb,$file,91);
					chmod($file,0777); }

					$date = mdata(datanow());
					$dane[$i] = array(
										'photo_file' => $name[$i],
										'photo_exif' => $exif[$i],
										'photo_date' => $date,
										'photo_show' => 0
									);
			} else {

				echo "<div class=\"error\">";
				echo _("zdjęcie nr.");
				echo " ".$i." ";
				echo _("nie zostało przesłane...");
				echo "</div>";

			}

			$i++;
		}

		$i=0;
		while($i<count($dane)) {

			$db->insert_array(_pre_."photo", $dane[$i]);
			if ($sghook->hooks_exist('photo_insert')) {
			    $sghook->execute_hooks('photo_insert',$_FILES);
			}
			$i++;
		}

		echo photoEditForm();
		exit;

}

	if ( $_GET['set'] == 'photo_edit' || $_GET['set'] == 'editablephoto' ) {

		if($_POST['delete'] == 1) {

			$r = $db->select("SELECT * FROM "._pre_."photo WHERE photo_id=".$_POST['id']);
			$row = $db->get_row($r,'MYSQL_ASSOC');

			$file = $row['photo_file'];
			@unlink("../photos/".$file.".jpg");
			@unlink("../photos/".$file."_m.jpg");
			@unlink("../photos/".$file."_s.jpg");

			@$db->select("DELETE FROM "._pre_."photo WHERE photo_id=".$row['photo_id']);

			if ($sghook->hooks_exist('photo_delete')) {
			    $sghook->execute_hooks('photo_delete',$row['photo_id']);
			}

			$akcja = _("usunięto");

		} else {

			$akcja = _("zapisano");
			$dane = array	(
								'photo_title' => $_POST['title'],
								'photo_desc' => $_POST['desc'],
								'photo_cat_id' => $_POST['kategoria'],
								'photo_show' => $_POST['public']
							);

			$db->update_array(_pre_."photo",$dane, "photo_id=".$_POST['id']);
			if ($sghook->hooks_exist('photo_save')) {
				$sghook->execute_hooks('photo_save',$_POST);
			}
		}

		if ($_GET['set'] != 'editablephoto') {

			echo photoEditForm();

  		} else {

			echo "<div class=\"ok\">".$akcja."</div>";

		}

		exit;

	}

	if ($_GET['id_photo']) {

		$r = $db->select("SELECT * FROM "._pre_."photo WHERE photo_id = ".$_GET['id_photo']);
		$row = $db->get_row($r,'MYSQL_ASSOC');

		if ($row['photo_show']==1)
			$check = " checked=\"checked\"";

  		$form 	 = '<form id="photoedit" action="setup-save.php?set=editablephoto" method="post" name="photoedit">';
  		$form 	.= '<div class="form">
						<div class="c">
							<img src="../photos/'.$row['photo_file'].'_m.jpg" alt="" />
							<input type="hidden" name="id" id="id" value="'.$row['photo_id'].'" />
						</div>
					</div>
					<div class="clr"></div>';
		$form	.= '<div class="form">
						<div class="l"><label for="kategoria">';
						$form .= _("Kategoria zdjęcia");
						$form .=':</label>
						<select name="kategoria" id="kategoria"><option value="0">'; $form .= _("--wybierz kategorię--"); $form .='</option>'.selectCategories($row['photo_cat_id']).'</select>
						</div>
					</div>
					<div class="clr"></div>';
		$form 	.= '<div class="form">
						<div class="l"><label for="title">';
		$form 	.= _("Tytuł zdjęcia");
		$form 	.= ':</label>
						<input type="text" name="title" id="title" value="'.$row['photo_title'].'"/>
					</div>
				</div>
				<div class="clr"></div>';
		$form 	.= '<div class="form">
						<div class="l"><label for="desc">';
		$form 	.= _("Opis zdjęcia");
		$form 	.= ':</label>
						</div>
						<div class="l">
							<textarea name="desc" id="desc">'.$row['photo_desc'].'</textarea>
						</div>
					</div>
					<div class="clr"></div>';
		$form 	.= '<div class="form">
						<div class="l"><label for="public">';
		$form 	.= _("Publikuj");
		$form 	.=':</label>
						<input type="checkbox" name="public" id="public" value="1"'.$check.' />
						</div>
					</div>
					<div class="clr"></div>';
		$form 	.= '<div class="form">
						<div class="l"><label for="delete">
							<strong>';
		$form 	.= _("Usuń");
		$form 	.=':</label>
							</strong>
							<input type="checkbox" name="delete" id="delete" value="1" />
						</div>
					</div>
					<div class="clr"></div>';

		if ($sghook->hooks_exist('photo')) {
			$form .= $sghook->execute_hooks('photo',$_GET);
		}

		$form 	.= '<div class="form">
						<div class="c">
							<input type="submit" name="submit" value="'; $form .= _("aktualizuj"); $form .='" id="send_aktual_photo" class="button" onclick="saveEditablePhoto(); return false;" />
						</div>
					</div>
					<div class="clr"></div>
					</form> ';
		echo $form;
		exit;

	}

	if ($_GET['set'] == 'add_note') {
		function pre_clear_code($code) {
			$code = preg_replace_callback("#\<pre(.*?)\>(.*?)\<\/pre\>#is",'pre_clear_code_callback',$code);
			return $code;
		}
		function pre_clear_code_callback($matches) {
			//$matches[2] = htmlspecialchars($matches[2]);
			return '<pre'.$matches[1].'>'.$matches[2].'</pre>';
		}
		$_POST['tekst'] = pre_clear_code($_POST['tekst']);
		$date = mdata(datanow());
		$_POST = mysql_real_escape_array($_POST);
		$text = $_POST['tekst'];
		$text = preg_replace('#(\\\r)?(\\\n)#',"\n",$text);


			if ($_POST['id'] > 0 ) {

				$dane = array(
								'news_title' => strip_tags($_POST['title']),
								'news_text' => $text,
								'news_show' => $_POST['public']
							);

				$db->update_array(_pre_."blog",$dane,"news_id=".$_POST['id']); $akcja = _("wpis zaktualizowano");


			} else {

				$dane = array(
								'news_title' => strip_tags($_POST['title']),
								'news_text' => $_POST['tekst'],
								'news_show' => $_POST['public'],
								'news_date' => $date
							);

				$db->insert_array(_pre_."blog",$dane); $akcja = _("wpis zapisany");
				$r = $db->select("SELECT news_id FROM "._pre_."blog ORDER BY news_id DESC LIMIT 0,1;");
				$row = $db->get_row($r,'MYSQL_ASSOC');
				$_POST['id'] = $row['news_id'];

			}
			if ($sghook->hooks_exist('post_save')) {

				$sghook->execute_hooks('post_save',$_POST);
			}
			echo '<div class="ok">'.$akcja.'</div>';
			exit;
	}

	if ($_GET['set'] == 'getupcat') {

		$r = $db->select("SELECT cat_sub_id FROM "._pre_."category WHERE cat_id = ".$_POST['idp']);
		$row = $db->get_row($r,'MYSQL_ASSOC');
		echo $row['cat_sub_id'];
		exit;
	}

	if ($_GET['set'] == 'editnews') {

		$dane = array(
						'news_show' => $_POST['akcja']
					);

		$db->update_array(_pre_."blog",$dane,"news_id=".$_POST['id']);
		exit;
	}

	if ($_GET['set'] == 'delnews') {

		$db->select("DELETE FROM "._pre_."blog WHERE news_id=".$_POST['id']);
		exit;
	}

	if ($_GET['set'] == 'editpage') {

		$r= $db->select("SELECT * FROM "._pre_."page");
		$row = $db->get_row($r,'MYSQL_ASSOC');

		$_POST = mysql_real_escape_array($_POST);

		$dane = array(
						'page_title' => strip_tags($_POST['title']),
	      				'page_desc' =>$_POST['tekst']
					);

		if ($row) {

			$db->update_array(_pre_."page",$dane,"page_id=".$row['page_id']);

			echo '<div class="ok">';
			echo _("stronę zaktualizowano");
			echo '</div>';

		} else {

			$db->insert_array(_pre_."page",$dane);

			echo '<div class="ok">';
			echo _("stronę stworzono");
			echo '</div>';

		}

		exit;
	}

	if ($_GET['set'] == 'editcom') {

		if (preg_match('/[0-9]+/',$_POST['del']))
			$db->select("DELETE FROM "._pre_."comments WHERE com_id = ".(int)$_POST['del']);

		if (preg_match('/[0-9]+/',$_POST['pub'])) {

			$r=$db->select("SELECT com_show FROM "._pre_."comments WHERE com_id = ".$_POST['pub']);

  			$kom = $db->get_row($r,'MYSQL_ASSOC');
  			if ( $kom['com_show'] == 1 )
				$show = 0;

			if ( $kom['com_show'] == 0 )
				$show = 1;

  			$dane = array( 'com_show' => $show );
			$db->update_array(_pre_."comments",$dane,"com_id=".(int)$_POST['pub']);

		}
		exit;
	}

@header("Location: setup.php?save=ok");

} else {

echo "no way...";
exit;

}
?>
